package com.demo.springboot.controller;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MockMvcBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

import static org.junit.Assert.*;

/**
 * 测试Controller方法二：
 * @WebMvcTest(controllers = UserController.class)
 * 不需要配置为Web环境，但是需要指定要测试的Controller
 * 这种方法只加载Controller，不会加载Spring容器，controller里面的一些依赖，需要自己mock
 *
 * 解决方法：
 * 替换 @WebMvcTest(controllers = UserController.class) 为
 * @SpringBootTest
 * @AutoConfigureMockMvc
 *
 * 详见 UserControllerTest3
 */
@RunWith(SpringRunner.class)
@WebMvcTest(controllers = UserController.class)
public class UserControllerTest2 {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void home() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/user/home")).andExpect(MockMvcResultMatchers.status().isOk());
        mockMvc.perform(MockMvcRequestBuilders.get("/user/home")).andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.content().string("user-home"));
    }

    @Test
    public void show() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/user/show").param("name","zll")).andExpect(MockMvcResultMatchers.status().isOk());
        mockMvc.perform(MockMvcRequestBuilders.get("/user/show").param("name","zll")).andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.content().string("user-show-name=zll"));
    }
}